package logic

import (
	"context"
	"errors"
	"hema-fresh/models/mysql"

	"hema-fresh/hemarpc/hemarpc"
	"hema-fresh/hemarpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddProductLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddProductLogic {
	return &AddProductLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddProductLogic) AddProduct(in *hemarpc.AddProductRequest) (*hemarpc.AddProductResponse, error) {
	// todo: add your logic here and delete this line
	var data mysql.Product
	mysql.DB.Debug().Where("name = ?", in.Name).Find(&data)
	if data.ID != 0 {
		return nil, errors.New("该商品已存在，请勿重复添加")
	}
	product := mysql.Product{
		Name:         in.Name,
		Price:        float64(in.Price),
		Stock:        int(in.Stock),
		CategoryName: in.CategoryName,
	}
	err := mysql.DB.Debug().Create(&product).Error
	if err != nil {
		return nil, errors.New("failed")
	}

	category := mysql.Category{
		CateName: in.CategoryName,
	}

	mysql.DB.Debug().Create(&category)

	return &hemarpc.AddProductResponse{
		ProductId:  int64(product.ID),
		CategoryId: int64(category.ID),
	}, nil
}
